package com.cyj.user.controller;

import com.cyj.user.entity.User;
import com.cyj.user.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Controller
@RequestMapping("users")
public class UserController {
    @Autowired
    private UserService userService;

    // 显示用户列表，需要登录验证
    @GetMapping("/list")
    public String listUsers(Model model, @SessionAttribute("loggedInUser") User loggedInUser) {
        if (loggedInUser == null) {
            return "redirect:/login";
        }
        List<User> users = userService.selectAllUsers();
        model.addAttribute("users", users);
        return "/list";
    }
//    @GetMapping("/list")
//    public String listUsers(Model model ){
//
//        List<User> users = userService.selectAllUsers();
//        model.addAttribute("users", users);
//        return "/list";
//    }
    // 显示添加用户页面
    @GetMapping("/add")
    public String showAddUserForm() {
        return "/add";
    }

    // 处理添加用户请求
    @PostMapping("/addUser")
    public String addUser(@ModelAttribute User user) {
        userService.insertUser(user);
        return "redirect:/users/list";
    }

    // 显示修改用户页面
    @GetMapping("/edit")
    public String showEditUserForm(@RequestParam("id") Integer id, Model model, @SessionAttribute("loggedInUser") User loggedInUser) {
        User user = userService.selectUserById(id);
        if (loggedInUser == null || (!loggedInUser.getuCode().equals(id) && loggedInUser.getuType() == 0)) {
            return "redirect:/users/list";
        }
        model.addAttribute("user", user);
        return "/edit";
    }

    // 处理修改用户请求
    @PostMapping("/editUser")
    public String editUser(@ModelAttribute User user) {
//        user.setuCode(id);
        userService.updateUser(user);
        return "redirect:/users/list";
    }

    // 处理删除用户请求
    @GetMapping("/delete")
    public String deleteUser(@RequestParam("id") Integer id, @SessionAttribute("loggedInUser") User loggedInUser) {
        if (loggedInUser == null || (!loggedInUser.getuCode().equals(id) && loggedInUser.getuType() == 0)) {
            return "redirect:/users/list";
        }
        userService.deleteUserById(id);
        return "redirect:/users/list";
    }
}